/**
 *    Copyright (C) 2009 Victor Smirnov <aist11@gmail.com>
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *    See LICENSE.exceptions in the root folder of this project for possible
 *    exceptions
 *
 */

#include <cubefs/core/tools/plugin.hpp>
#include <cubefs/api/exceptions.hpp>

#include <iostream>
#include <fstream>

#include <elf.h>

#define CUBEFS_SOURCE "api-impl/posix/plugin.cpp:" CUBEFS_AT

namespace cubefs{ namespace tools {

using namespace std;
using namespace cubefs::api;

SystemDescriptor GetSystemDescriptor()
{
	SystemDescriptor descr;
	descr.os_ 	= OS::POSIX;

#ifdef __x86_64
	descr.arch_	= Architecture::X86_64;
#else
	descr.arch_	= Architecture::I386;
#endif

	return descr;
}

ResourceDescriptor Plugin::GetResouerceDescriptor(Configurator* config, const File& path)
{
	filebuf file;
	file.open(path.GetPath().c_str(), ios_base::in);

	if (file.is_open())
	{
		ResourceDescriptor descr;

		Elf32_Ehdr elf_hdr;

		streamsize size = EI_NIDENT + sizeof(uint16_t)*2;
		if (size == file.sgetn((char*)&elf_hdr, size))
		{
			if (elf_hdr.e_ident[EI_MAG0] == ELFMAG0 && elf_hdr.e_ident[EI_MAG1] == ELFMAG1 &&
				elf_hdr.e_ident[EI_MAG2] == ELFMAG2 && elf_hdr.e_ident[EI_MAG3] == ELFMAG3 &&
				(elf_hdr.e_type == ET_REL || elf_hdr.e_type == ET_DYN))
			{
				descr.plugin_ = true;

				switch (elf_hdr.e_machine)
				{
					case EM_386: 	descr.arch_ = Architecture::I386; 	break;
					case EM_X86_64: descr.arch_ = Architecture::X86_64; break;
					case EM_ARM: 	descr.arch_ = Architecture::ARM32; 	break;

					default:		descr.plugin_ = false;
				}
			}
			else {
				descr.plugin_ = false;
			}
		}
		else {
			file.close();
			throw FileException(CUBEFS_SOURCE, "Can't read elf header from file", path.GetPath());
		}

		file.close();
		return descr;
	}
	else {
		throw FileException(CUBEFS_SOURCE, "Can't open file for reading", path.GetPath());
	}
}

}}
